<template>
    <div>
        <el-form ref="form" label-width="80px" size="normal" :model="spu">
            <el-form-item label="SPU名称">
                <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select placeholder="请选择品牌" v-model="spu.tmId">
                    <el-option :label="tm.tmName" :value="tm.id" v-for="(tm, index) in tradeMarkList"
                        :key="tm.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" placeholder="SPU名称" rows="4" resize="none" v-model="spu.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <!-- 上传图片,action是指上传图片的地址 -->
                <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess"
                    :file-list="spuImageList">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-select :placeholder="`还有${unSelectedSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
                    <el-option :label="unselect.name" :value="`${unselect.id}:${unselect.name}`"
                        v-for="(unselect, index) in unSelectedSaleAttr" :key="unselect.id"></el-option>
                </el-select>
                <el-button type="primary" size="default" icon="el-icon-plus" :disabled="!attrIdAndAttrName"
                    @click="addSaleAttr">添加销售属性</el-button>
                <!-- 展示的是当前spu已选的销售属性 -->
                <el-table border style="width: 100%;" :data="spu.spuSaleAttrList">
                    <el-table-column type="index" align="center" label="序号" width="80px"></el-table-column>
                    <el-table-column prop="saleAttrName" label="属性名" width="width"></el-table-column>
                    <!--  -->
                    <el-table-column prop="prop" label="属性名称列表" width="width">
                        <template slot-scope='{row,$index}'>
                            <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable
                                :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                                {{ tag.saleAttrValueName }}
                            </el-tag>
                            <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" :ref="$index"
                                size="small" @keyup.enter.native="$event.target.blur"
                                @blur="handleInputConfirm(row, $index)">
                            </el-input>
                            <!-- @click="showInput" -->
                            <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row, $index)">+
                                添加</el-button>

                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="width">
                        <template slot-scope='{row,$index}'>
                            <el-button type="danger" icon="el-icon-delete" size="mini"
                                @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addOrUpdateSpu" :disabled="disableSave">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
export default {
    name: 'SpuForm',
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            //存储spu属性信息
            spu: {
                category3Id: 0,//三级分类的id
                tmId: '',//品牌的id
                description: "",//描述
                spuName: "",//spu名称
                //收集spu图片
                spuImageList: [
                    /* {
                        id: 0,
                        imgName: "string",
                        imgUrl: "string",
                        spuId: 0
                    } */
                ],
                //平台属性与属性值的收集
                spuSaleAttrList: [
                    /* {
                        baseSaleAttrId: 0,
                        id: 0,
                        saleAttrName: "string",
                        spuId: 0,
                        spuSaleAttrValueList: [
                            {
                                baseSaleAttrId: 0,
                                id: 0,
                                isChecked: "string",
                                saleAttrName: "string",
                                saleAttrValueName: "string",
                                spuId: 0
                            }
                        ]
                    } */
                ],
            },
            tradeMarkList: [],//品牌信息
            spuImageList: [],//spu图片信息
            saleAttrList: [],//销售属性信息
            attrIdAndAttrName: '',//收集未选择的销售属性id
            disableSave: false
        }
    },
    methods: {
        //照片墙移除
        handleRemove(file, fileList) {
            // console.log(file, fileList);
            this.spuImageList = fileList
        },
        //照片预览
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //照片添加
        handleSuccess(response, file, fileList) {
            this.spuImageList = fileList
        },
        //点击修改某个spu的时候发请求获取spu数据
        async initSpuData(spu) {
            let spuResult = await this.$API.spu.reqSpu(spu.id)
            // console.log(spuResult);
            if (spuResult.code == 200) {
                this.spu = spuResult.data
            }
            let tradeMarkResult = await this.$API.spu.reqTradeMarkList()
            // console.log(tradeMarkResult);
            if (tradeMarkResult.code == 200) {
                this.tradeMarkList = tradeMarkResult.data
            }
            let spuImageListResult = await this.$API.spu.reqSpuImageList(spu.id)
            // console.log(spuImageListResult);
            if (spuImageListResult.code == 200) {
                let listArr = spuImageListResult.data
                listArr.forEach(item => {
                    item.name = item.imgName
                    item.url = item.imgUrl
                })
                this.spuImageList = listArr
            }
            let saleResult = await this.$API.spu.reqBaseSaleAttrList()
            // console.log(saleResult);
            if (saleResult.code == 200) {
                this.saleAttrList = saleResult.data
            }
        },
        //添加销售属性操作
        addSaleAttr() {
            const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
            let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
            this.spu.spuSaleAttrList.push(newSaleAttr)
            this.attrIdAndAttrName = ''
            this.disableSave = true
        },
        //添加销售属性里面的属性值
        addSaleAttrValue(row, index) {
            //控制button与input框切换
            this.$set(row, 'inputVisible', true)
            this.$set(row, 'inputValue', '')
            this.$nextTick(() => {
                //获取相应的表单元素并聚焦
                this.$refs[index].focus()
            })
        },
        //失去焦点的事件input  -> buttton
        handleInputConfirm(row, index) {
            //解构
            const { baseSaleAttrId, inputValue } = row
            //属性值不能为空
            if (inputValue.trim() == '') {
                this.$message('属性值不能为空!')
                this.$refs[index].focus()
                return
            }
            //属性值不能重复   isRepeat为false则是重复了,true则是没重复
            let isRepeat = row.spuSaleAttrValueList.every(item => item.saleAttrValueName != inputValue)
            if (isRepeat == false) {
                this.$message('请不要输入重复的属性值')
                this.$refs[index].focus()
                this.disableSave = true
                return
            }
            //新增的销售属性
            let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
            //添加进数组
            row.spuSaleAttrValueList.push(newSaleAttrValue)
            row.inputVisible = false
            this.disableSave = false
        },
        //保存或者更新spu
        async addOrUpdateSpu() {
            this.spu.spuImageList = this.spuImageList.map(item => {
                return {
                    imgNmae: item.name,
                    imgUrl: (item.response && item.response.data) || item.url
                }
            })
            let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
            if (result.code == 200) {
                this.$message({ type: 'success', message: '保存成功' })
                this.$emit("changeScene", {
                    scene: 0,
                    flag: this.spu.id ? "修改" : "添加",
                });
                // this.$emit("changeScene", 0);
                //清空数据
                Object.assign(this._data, this.$options.data());
            }
        },
        //点击添加spu按钮的时候发请求的函数
        async addSpuData(category3Id) {
            //首先先清空数据
            Object.assign(this._data, this.$options.data());

            //添加SPU的时候收集三级分类的id
            this.spu.category3Id = category3Id;
            //获取品牌的信息
            let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
            if (tradeMarkResult.code == 200) {
                this.tradeMarkList = tradeMarkResult.data;
            }
            //获取平台全部的销售属性
            let saleResult = await this.$API.spu.reqBaseSaleAttrList();
            if (saleResult.code == 200) {
                this.saleAttrList = saleResult.data;
            }
        },
        cancel() {
            this.$emit("changeScene", {
                scene: 0,
                flag: ''
            });
            //清理数据
            //Object.assign:es6中新增的方法可以合并对象
            //组件实例this._data,可以操作data当中响应式数据
            //this.$options可以获取配置对象，配置对象的data函数执行，返回的响应式数据为空的
            Object.assign(this._data, this.$options.data());
        }
    },
    computed: {
        unSelectedSaleAttr() {
            //数组过滤方法,过滤出用户需要的元素,并返回一个新的数据
            let result = this.saleAttrList.filter(item => {
                //every数组的方法会返回一个布尔值[真/假]
                return this.spu.spuSaleAttrList.every(item1 => {
                    return item.name != item1.saleAttrName
                })
            })
            return result
        }
    }

}
</script>
<style>
.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
